<?php
namespace Fc;

use GuzzleHttp\Exception\RequestException;


class SDKClient {
    public $endpoint;
    public $accessKey;
    public $secretKey;
    public $protocol;
    public $method;

    public function __construct(Config $config) {
        if (!$config->endpoint) {
            throw new \InvalidArgumentException('endpoint is required');
        }
        if (!$config->accessKey || !$config->secretKey) {
            throw new \InvalidArgumentException('aksk is required');
        }

        $this->endpoint = $config->endpoint;
        $this->accessKey = $config->accessKey;
        $this->secretKey = $config->secretKey;
        $this->protocol = $config->protocol ?? 'HTTPS';
        $this->method = $config->method ?? 'POST';
    }


    public function doRequest($requestConfig) {
        try {
            // 构建CTAPIrequest对象
            $url = sprintf('%s://%s%s', $this->protocol, $this->endpoint, $requestConfig['url']);
            $method = $requestConfig["method"] ?? $this->method;
            $headers = $requestConfig['headers'];
            $data = $requestConfig['data'];
            $query = $requestConfig['query'];
            $CTAPIrequest = new CTAPIrequest($url, $method, $headers, $data, $query);


            $cre = new Credentials($this->accessKey, $this->secretKey);
            $Response = $cre->doCTAPIRequest($CTAPIrequest);
            return $Response;
        } catch (RequestException $e) {
            printf("Client do request return with error: %s\n", $e->getMessage());
            return $e;
        }
    }
}
